"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { GAME_CONFIG, GameState, BirdState, Pipe, GameStateData } from "@/lib/game-config";

export function useGame() {
  // 游戏状态
  const [gameState, setGameState] = useState<GameStateData>({
    state: GAME_CONFIG.GAME_STATES.READY,
    bird: {
      y: GAME_CONFIG.GAME_HEIGHT / 2 - GAME_CONFIG.BIRD_HEIGHT / 2,
      velocity: 0,
      rotation: 0
    },
    pipes: [],
    score: 0,
    highScore: 0,
    speed: GAME_CONFIG.INITIAL_SPEED
  });

  // 动画帧引用
  const animationFrameRef = useRef<number | null>(null);
  
  // 上一帧时间戳
  const lastTimeRef = useRef<number>(0);
  
  // 管道生成计时器
  const pipeTimerRef = useRef<NodeJS.Timeout | null>(null);
  
  // 管道ID计数器
  const pipeIdCounterRef = useRef<number>(0);

  // 游戏开始时间引用
  const gameStartTimeRef = useRef<number>(0);

  // 游戏循环 - 优化更新逻辑
  const gameLoop = useCallback((time: number) => {
    // 继续游戏循环 - 确保在任何情况下都会请求下一帧
    animationFrameRef.current = requestAnimationFrame(gameLoop);
    
    // 使用函数式更新，获取最新状态
    setGameState(prev => {
      // 记录调用和当前状态
      console.log("gameLoop被调用，当前状态:", prev.state);
      
      if (prev.state !== GAME_CONFIG.GAME_STATES.PLAYING) {
        // 如果不是PLAYING状态，不更新游戏状态
        return prev;
      }

      console.log("游戏循环运行中");
      const deltaTime = time - lastTimeRef.current;
      lastTimeRef.current = time;
      
      // 计算游戏已运行时间（毫秒）
      const gameRunningTime = time - gameStartTimeRef.current;
      console.log("游戏运行时间:", gameRunningTime, "ms");

      // 更新鸟的位置和速度
      const newVelocity = Math.min(
        prev.bird.velocity + GAME_CONFIG.BIRD_GRAVITY,
        GAME_CONFIG.BIRD_TERMINAL_VELOCITY
      );
      
      const newY = prev.bird.y + newVelocity;
      
      // 详细记录鸟的位置和速度更新
      console.log("游戏循环 - 位置更新:", {
        oldY: prev.bird.y,
        oldVelocity: prev.bird.velocity,
        gravity: GAME_CONFIG.BIRD_GRAVITY,
        newVelocity: newVelocity,
        newY: newY,
        deltaY: newY - prev.bird.y
      });
      
      // 计算鸟的旋转角度 (基于速度)
      const newRotation = Math.min(
        Math.max(newVelocity * 3, -30), // 上升时最多旋转-30度
        90 // 下降时最多旋转90度
      );

      // 更新管道位置
      const currentSpeed = prev.speed;
      const newPipes = prev.pipes.map(pipe => ({
        ...pipe,
        x: pipe.x - currentSpeed
      })).filter(pipe => pipe.x > -GAME_CONFIG.PIPE_WIDTH); // 移除已经移出屏幕的管道

      // 检查得分
      let newScore = prev.score;
      const updatedPipes = newPipes.map(pipe => {
        if (!pipe.passed && pipe.x < GAME_CONFIG.GAME_WIDTH / 2 - GAME_CONFIG.PIPE_WIDTH / 2) {
          newScore += 1;
          return { ...pipe, passed: true };
        }
        return pipe;
      });

      // 检查碰撞
      const birdHitbox = {
        x: GAME_CONFIG.GAME_WIDTH / 2 - GAME_CONFIG.BIRD_WIDTH / 2 + GAME_CONFIG.COLLISION_PADDING,
        y: newY + GAME_CONFIG.COLLISION_PADDING,
        width: GAME_CONFIG.BIRD_WIDTH - GAME_CONFIG.COLLISION_PADDING * 2,
        height: GAME_CONFIG.BIRD_HEIGHT - GAME_CONFIG.COLLISION_PADDING * 2
      };
      
      // 游戏开始后3秒内不检测碰撞（延长安全期）
      const safetyPeriod = 3000; // 3秒
      const isInSafetyPeriod = gameRunningTime < safetyPeriod;
      
      // 检查是否碰到地面（安全期内不检测）
      let hitGround = false;
      if (!isInSafetyPeriod) {
        hitGround = newY + GAME_CONFIG.BIRD_HEIGHT >= GAME_CONFIG.GAME_HEIGHT - GAME_CONFIG.GROUND_HEIGHT;
      }
      
      // 添加详细调试日志
      console.log("碰撞检测详情:", {
        gameRunningTime,
        isInSafetyPeriod,
        birdY: newY,
        birdHeight: GAME_CONFIG.BIRD_HEIGHT,
        groundY: GAME_CONFIG.GAME_HEIGHT - GAME_CONFIG.GROUND_HEIGHT,
        hitGround: hitGround,
        gameState: prev.state
      });
      
      // 检查是否碰到管道（安全期内不检测）
      let hitPipe = false;
      if (!isInSafetyPeriod) {
        hitPipe = updatedPipes.some(pipe => {
          // 上管道碰撞检测
          const hitTopPipe = 
            birdHitbox.x + birdHitbox.width > pipe.x &&
            birdHitbox.x < pipe.x + GAME_CONFIG.PIPE_WIDTH &&
            birdHitbox.y < pipe.topHeight;
          
          // 下管道碰撞检测
          const hitBottomPipe = 
            birdHitbox.x + birdHitbox.width > pipe.x &&
            birdHitbox.x < pipe.x + GAME_CONFIG.PIPE_WIDTH &&
            birdHitbox.y + birdHitbox.height > pipe.topHeight + GAME_CONFIG.PIPE_GAP;
          
          return hitTopPipe || hitBottomPipe;
        });
      }

      // 如果发生碰撞，游戏结束
      if (hitGround || hitPipe) {
        // 清除管道生成定时器
        if (pipeTimerRef.current) {
          clearInterval(pipeTimerRef.current);
          pipeTimerRef.current = null;
        }

        // 更新最高分
        const newHighScore = Math.max(prev.highScore, newScore);
        if (newHighScore > prev.highScore) {
          localStorage.setItem(GAME_CONFIG.STORAGE_KEYS.HIGH_SCORE, newHighScore.toString());
        }

        return {
          ...prev,
          state: GAME_CONFIG.GAME_STATES.GAME_OVER,
          bird: {
            ...prev.bird,
            y: hitGround ? GAME_CONFIG.GAME_HEIGHT - GAME_CONFIG.GROUND_HEIGHT - GAME_CONFIG.BIRD_HEIGHT : newY,
            velocity: newVelocity,
            rotation: 90 // 鸟坠落时旋转90度
          },
          pipes: updatedPipes,
          score: newScore,
          highScore: newHighScore
        };
      }

      // 增加游戏速度
      const newSpeed = Math.min(
        prev.speed + GAME_CONFIG.SPEED_INCREMENT * deltaTime,
        GAME_CONFIG.MAX_SPEED
      );

      // 返回更新后的游戏状态
      return {
        ...prev,
        bird: {
          y: newY,
          velocity: newVelocity,
          rotation: newRotation
        },
        pipes: updatedPipes,
        score: newScore,
        speed: newSpeed
      };
    });
    
    // 注意：我们已经在函数开始处请求了下一帧，这里不需要重复
  }, []); // 移除依赖，避免闭包问题

  // 生成新管道
  const generatePipe = useCallback(() => {
    console.log("生成新管道函数被调用");
    
    // 使用函数式更新，直接从prev获取当前状态，避免闭包问题
    setGameState(prev => {
      console.log("generatePipe中的当前状态:", prev.state);
      
      if (prev.state !== GAME_CONFIG.GAME_STATES.PLAYING) {
        console.log("游戏不在进行中，不生成管道");
        return prev;
      }

      // 随机生成上管道高度
      const minTopHeight = GAME_CONFIG.PIPE_MIN_HEIGHT;
      const maxTopHeight = GAME_CONFIG.GAME_HEIGHT - GAME_CONFIG.PIPE_GAP - GAME_CONFIG.PIPE_MIN_HEIGHT - GAME_CONFIG.GROUND_HEIGHT;
      const topHeight = Math.floor(Math.random() * (maxTopHeight - minTopHeight + 1)) + minTopHeight;

      // 创建新管道
      const newPipe: Pipe = {
        id: pipeIdCounterRef.current++,
        x: GAME_CONFIG.GAME_WIDTH,
        topHeight,
        passed: false
      };

      console.log("生成新管道:", newPipe);
      return {
        ...prev,
        pipes: [...prev.pipes, newPipe]
      };
    });
  }, []); // 移除依赖，避免闭包问题


  // 初始化游戏
  useEffect(() => {
    console.log("初始化游戏 - 组件挂载");
    
    // 从本地存储加载最高分
    const savedHighScore = localStorage.getItem(GAME_CONFIG.STORAGE_KEYS.HIGH_SCORE);
    if (savedHighScore) {
      setGameState(prev => ({
        ...prev,
        highScore: parseInt(savedHighScore, 10)
      }));
    }
    
    // 立即启动游戏循环，即使在READY状态也保持运行
    console.log("初始启动游戏循环");
    lastTimeRef.current = performance.now();
    animationFrameRef.current = requestAnimationFrame(gameLoop);

    // 清理函数
    return () => {
      console.log("清理游戏资源 - 组件卸载");
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
      if (pipeTimerRef.current) {
        clearInterval(pipeTimerRef.current);
      }
    };
  }, [gameLoop]); // 添加gameLoop作为依赖

  // 开始游戏
  const startGame = useCallback(() => {
    console.log("startGame被调用");
    
    // 使用函数式更新，直接从prev获取当前状态，避免闭包问题
    setGameState(prev => {
      console.log("startGame中的当前状态:", prev.state);
      
      if (prev.state !== GAME_CONFIG.GAME_STATES.READY && 
          prev.state !== GAME_CONFIG.GAME_STATES.GAME_OVER) {
        console.log("游戏已经在进行中，不重新开始");
        return prev;
      }

      // 重置游戏状态
      console.log("重置游戏状态");
      return {
        ...prev,
        state: GAME_CONFIG.GAME_STATES.PLAYING,
        bird: {
          // 将小鸟放在更高的位置，避免立即碰到地面
          y: GAME_CONFIG.GAME_HEIGHT / 3 - GAME_CONFIG.BIRD_HEIGHT / 2,
          // 给小鸟一个轻微的向上初速度，避免立即下落
          velocity: GAME_CONFIG.BIRD_JUMP_STRENGTH,
          rotation: 0
        },
        pipes: [],
        score: 0,
        speed: GAME_CONFIG.INITIAL_SPEED
      };
    });

    // 开始游戏循环
    console.log("启动游戏循环");
    const currentTime = performance.now();
    lastTimeRef.current = currentTime;
    gameStartTimeRef.current = currentTime; // 设置游戏开始时间
    
    // 开始生成管道
    console.log("启动管道生成器");
    if (pipeTimerRef.current) {
      clearInterval(pipeTimerRef.current);
    }
    pipeTimerRef.current = setInterval(generatePipe, GAME_CONFIG.PIPE_SPAWN_INTERVAL);
  }, []); // 移除依赖，避免闭包问题



  // 鸟跳跃 - 优化依赖项
  const jump = useCallback(() => {
    console.log("跳跃函数被调用");
    console.log("BIRD_JUMP_STRENGTH值:", GAME_CONFIG.BIRD_JUMP_STRENGTH);
    
    // 使用函数式更新，直接从prev获取当前状态，避免闭包问题
    setGameState(prev => {
      console.log("jump中的当前游戏状态:", prev.state);
      console.log("jump前的鸟位置:", prev.bird.y);
      console.log("jump前的鸟速度:", prev.bird.velocity);
      
      if (prev.state === GAME_CONFIG.GAME_STATES.PLAYING) {
        console.log("设置鸟的向上速度为:", GAME_CONFIG.BIRD_JUMP_STRENGTH);
        
        return {
          ...prev,
          bird: {
            ...prev.bird,
            velocity: GAME_CONFIG.BIRD_JUMP_STRENGTH
          }
        };
      } else if (prev.state === GAME_CONFIG.GAME_STATES.READY || 
                prev.state === GAME_CONFIG.GAME_STATES.GAME_OVER) {
        console.log("准备开始游戏");
        
        // 设置游戏开始时间
        const currentTime = performance.now();
        lastTimeRef.current = currentTime;
        gameStartTimeRef.current = currentTime;
        
        // 开始生成管道 - 在状态更新的同时处理副作用
        setTimeout(() => {
          console.log("启动管道生成器");
          if (pipeTimerRef.current) {
            clearInterval(pipeTimerRef.current);
          }
          pipeTimerRef.current = setInterval(generatePipe, GAME_CONFIG.PIPE_SPAWN_INTERVAL);
        }, 0);
        
        return {
          ...prev,
          state: GAME_CONFIG.GAME_STATES.PLAYING,
          bird: {
            y: GAME_CONFIG.GAME_HEIGHT / 3 - GAME_CONFIG.BIRD_HEIGHT / 2,
            velocity: GAME_CONFIG.BIRD_JUMP_STRENGTH, // 直接给一个向上的初速度
            rotation: 0
          },
          pipes: [],
          score: 0,
          speed: GAME_CONFIG.INITIAL_SPEED
        };
      }
      
      console.log("状态未改变");
      return prev;
    });
  }, []); // 添加闭合括号和依赖数组

  return {
    gameState,
    jump,
    startGame
  };
}